﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using ZeroMQ;
using System.Threading;
using log4net;

namespace ZMQtoSMSService
{
    public partial class Service1 : ServiceBase
    {
        private Thread revThread,smsThread;
        delegate SMSModel revdelegate();
        ILog logger = log4net.LogManager.GetLogger("");
        string strFileName = "D:\\ZMQtoSMSlogs\\" + System.DateTime.Now.Date.ToString("yyyy-MM-dd") + ".txt";
        byte[] buffer = new byte[512];
        int len;
        string str;
        string speStr = "<*&\\\\@#//&*>";
        string monitorServiceName = "ZMQtoSMSService";

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            //try
            //{
            //    revdelegate rev = new revdelegate(Listener);
            //    AsyncCallback callback = new AsyncCallback(callbackMethod);
            //    rev.BeginInvoke(callback, rev);
            //}
            //catch(Exception ex)
            //{
            //    logger.Debug("aaaaaaaaaaaaaa");
            //}


            revThread = new Thread(Listener);
            revThread.Start();    
            
        }

        //static void callbackMethod(IAsyncResult Ias)
        //{

        //    revdelegate rev = (revdelegate)Ias.AsyncState;
        //    SMSModel sMSModel = rev.EndInvoke(Ias);
        //    SMSSend.SendSms_Action(sMSModel);
        //}

        protected override void OnStop()
        {
        }

        protected override void OnContinue()
        {
            //revThread.Abort();
            //revThread = new Thread(Listener);
            //revThread.Start(); 
        }


        private void Listener()
        {


            using (var context = ZmqContext.Create())
            {
                using (var socket = context.CreateSocket(SocketType.REP))
                {
                    socket.Bind("tcp://*:46666");
                    try
                    {
                        while (true)
                        {
                            SMSModel sMSModel = new SMSModel();
                            len = socket.Receive(buffer);
                            logger.Debug("接受到的字符串长度为：" + len.ToString());
                            str = Encoding.UTF8.GetString(buffer);
                            logger.Debug("接收到的字符串内容为：" + str);
                            // sMSModel.sysid = str.PadLeft(3,'0');
                            sMSModel.senderid = str.Substring(0, 3);
                            sMSModel.sysid = str.Substring(3, 8);
                            len = str.IndexOf(speStr);
                            sMSModel.message = str.Substring(11, len - 11);
                            logger.Debug(sMSModel.sysid + sMSModel.message + sMSModel.senderid);
                            //
                            socket.Send("Recieved:" + sMSModel.sysid + sMSModel.message + sMSModel.senderid, Encoding.UTF8);
                            SMSSend.SendSms_Action(sMSModel);
                            //return sMSModel;
                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Debug(ex.Message.ToString());
                        SMSModel sMSModel = new SMSModel();
                        sMSModel.senderid = "008";
                        sMSModel.sysid = "T1000147";
                        sMSModel.message = "ZMQtoSMSService发生异常";
                        socket.Send("Recieved:" + sMSModel.sysid + sMSModel.message + sMSModel.senderid, Encoding.UTF8);
                        SMSSend.SendSms_Action(sMSModel);
                        restertService(monitorServiceName);
                    }

                }
            } 
        }

        private void restertService(string serviceName)
        {
            ServiceController sc = new ServiceController(serviceName);
            if (sc.Status == ServiceControllerStatus.Running)
            {
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            sc.Start();
            sc.WaitForStatus(ServiceControllerStatus.Running);
            //sc.Refresh();
        }


    }
}
